package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.service.AuthCodeService;
import com.lagou.edu.pojo.AuthCode;
import org.hibernate.annotations.DynamicInsert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


@Service
@DynamicInsert
public class AuthCodeServiceImpl implements AuthCodeService {
    @Autowired
    private AuthCodeDao authCodeDao;

    @Override
    public Boolean canCreateEmail(String email) {
        if(existsCode(email)){
            return false;
        }else {
            return true;
        }
    }


    @Override
    public Boolean addAuthCode(String email, String code) {
        if(existsCode(email)){
            return false;
        }else {
            AuthCode authCode = new AuthCode();
            // 当前时间
            long createTime = System.currentTimeMillis();
            // 过期时间(当前时间+10分钟)
            long expireTime = createTime + 10 * 60 * 1000;
            //设置日期格式
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            authCode.setEmail(email);
            authCode.setCreatetime(df.format(new Date(createTime)));
            authCode.setExpiretime(df.format(new Date(expireTime)));
            authCode.setCode(code);
            authCodeDao.save(authCode);
            return true;
        }
    }


    @Override
    public Boolean existsCode(String email) {
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        Example<AuthCode> example = Example.of(authCode);
        return authCodeDao.exists(example);
    }


    @Override
    public Boolean correctCode(String email, String code) {
        AuthCode AuthCode = authCodeDao.findByEmail(email);
        if(code.equals(AuthCode.getCode())){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public String getCode() {
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            // 生成0~9的随机数
            int randomNum = random.nextInt(10);
            code = code + randomNum;
        }
        return code;
    }
}
